<template>
  <!--案件分配-->
  <section class="component case-distribution">
    <div class="top row middle-span">
      <div>
        共选择
        <span class="case-count">{{selectedCaseIds.length}}</span>条案件
      </div>
      <el-radio-group class="patterns" v-model="model.distributeMode">
        <el-radio :key="index" :label="parrent.value" @change="refreshData" v-for="(parrent,index) of patternCollection">{{parrent.name}}</el-radio>
      </el-radio-group>
    </div>
    <data-box :data="dataSet">
      <template slot="columns">
        <!--数据列区域-->
        <el-table-column :min-width="$helper.getColumnWidth(3)" label="委外方" prop="outsourceName"></el-table-column>
        <el-table-column :min-width="$helper.getColumnWidth(4)" label="当前持有案件数" prop="currentNum"></el-table-column>
        <el-table-column :min-width="$helper.getColumnWidth(4)" label="当前持有案件总金额" prop="currentAmt"></el-table-column>
        <el-table-column :min-width="$helper.getColumnWidth(4)" label="确认分配案件数">
          <template slot-scope="scope">
            <el-input
              :disabled="!isCustomerDistribution"
              :max="selectedCaseIds.length"
              :min="0"
              :precision="0"
              @blur="onNumBlur"
              type="number"
              v-model="scope.row.num"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column :min-width="$helper.getColumnWidth(4)" label="分配案件欠款金额" prop="amt" v-if="!isCustomerDistribution"></el-table-column>
        <el-table-column :formatter="computAllotCaseCount" :min-width="$helper.getColumnWidth(4)" label="分配后案件总数量" prop="sumNum"></el-table-column>
        <el-table-column :min-width="$helper.getColumnWidth(4)" label="分配后案件总金额" prop="sumAmt" v-if="!isCustomerDistribution"></el-table-column>
      </template>
    </data-box>

    <el-form :model="model" :rules="companyRules" label-width="120px" ref="form">
      <el-form-item label="委外到期时间" prop="outEndDate" v-if="!isLawsuit">
        <el-date-picker :picker-options="$common.datePickDisabledDate(1)" placeholder="请选择日期" type="date" v-model="model.outEndDate" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
    </el-form>

    <div class="operate-buttons">
      <el-button @click="emitPre">上一步</el-button>
      <el-button @click="emitClose">取 消</el-button>
      <el-button @click="submit">确定</el-button>
    </div>
  </section>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import { Dependencies } from "~/core/decorator";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { OutsourceStayService } from "~/services/domain-service/outsource-stay-manage.service";
import { OutsourceLawsuitStayService } from "~/services/domain-service/outsource-lawsuit-manage.service";
import { Form } from "element-ui";
import { DISTRIBUTION_TYPE } from "~/config/enum.config";

@Component({
  components: {}
})
export default class CaseDistribution extends Vue {
  @Dependencies(OutsourceStayService)
  private outsourceStayService: OutsourceStayService;
  @Dependencies(OutsourceLawsuitStayService)
  private outsourceLawsuitStayService: OutsourceLawsuitStayService;
  @Prop({
    required: true,
    default: () => []
  })
  private selectedCaseIds: string[];

  @Prop({
    required: true,
    default: () => []
  })
  private commissionIds: string[];
  private patternCollection = DISTRIBUTION_TYPE;

  /**
   * 是否全部数据
   */
  @Prop({ required: true })
  private isLawsuit: boolean;

  private dataSet: any[] = [];

  private model: any = {
    distributeMode: "BY_INTEGRATE",
    outEndDate: "",
    analyseId: ""
  };

  private companyRules: any = {
    outEndDate: [{ required: true, message: "请选择委外到期时间" }]
  };

  /**
   * 刷新分案预览数据
   */
  public refreshData() {
    const requestModel = {
      caseIds: this.selectedCaseIds,
      distributeMode: this.model.distributeMode,
      outsourceIds: this.commissionIds
    };
    if (!this.isLawsuit) {
      this.outsourceStayService
        .searchSplitPreview(requestModel)
        .subscribe(data => {
          this.model.analyseId = data.analyseId;
          this.dataSet = data.resDistModel;
        });
    } else {
      this.outsourceLawsuitStayService
        .searchSplitPreview(requestModel)
        .subscribe(data => {
          this.model.analyseId = data.analyseId;
          this.dataSet = data.resDistModel;
        });
    }
  }

  @Emit("pre")
  private emitPre() {
    this.resetData();
  }

  @Emit("close")
  private emitClose() {
    this.resetData();
  }

  @Emit("success")
  private emitSuccess() {
    this.emitClose();
    this.$message.success("案件分配成功");
  }

  /**
   * 计算输入后当前行人员的案件总数
   */
  private computAllotCaseCount(row: any) {
    const inputNum = Number.parseInt(row.num || "0");
    return inputNum + row.currentNum;
  }

  /**
   * 输入验证
   */
  private onNumBlur(e) {
    if (e.target.valueAsNumber > this.selectedCaseIds.length) {
      this.$message.error(e.target.validationMessage);
    } else {
      const alreadySum = this.dataSet.reduce(
        (a, c) => a + Number.parseInt(c.num || "0"),
        0
      );
      if (alreadySum > this.selectedCaseIds.length) {
        this.$message.error("输入数量不能大于选中分案数量");
      }
    }
  }

  private resetData() {
    this.model.distributeMode = "BY_INTEGRATE";
    this.model.analyseId = "";
    const form = this.$refs.form as Form;
    form.resetFields();
  }

  private submit() {
    const form = this.$refs.form as Form;
    form.validate(v => {
      if (!v) return;
      const caseCount = this.dataSet.reduce((a, c) => a + c.num, 0);
      if (caseCount > this.selectedCaseIds) {
        this.$message("确认分配案件数不能大于选择的案件总数");
        return;
      }
      this.model.caseIds = this.selectedCaseIds;
      this.model.outsourceIds = this.commissionIds;
      this.model.distributeNumber = this.dataSet.map(v => parseInt(v.num));
      this.model.distributeMode = this.model.distributeMode;
      this.distributionCase();
    });
  }

  private distributionCase() {
    if (!this.isLawsuit) {
      this.outsourceStayService
        .confirmDistributeCase(this.model)
        .subscribe(this.emitSuccess);
    } else {
      this.outsourceLawsuitStayService
        .confirmDistributeCase(this.model)
        .subscribe(this.emitSuccess);
    }
  }

  /**
   * 是否自定义分配
   */
  private get isCustomerDistribution() {
    return this.model.distributeMode === "BY_CUSTOMIZE";
  }
}
</script>
<style lang="less" scoped>
.component.case-distribution {
  .top {
    margin: 0 0 10px 12px;
    .case-count {
      display: inline-block;
      padding: 0 4px;
      font-weight: bold;
    }
    .patterns {
      margin-left: 40px;
      line-height: inherit !important;
    }
  }
}
</style>
